package cn.jieruoda.eb.store;

import cn.jieruoda.eb.store.domain.entity.StoreProduct;
import cn.jieruoda.eb.store.service.StoreProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api/store/products")
public class StoreController {

    @Autowired
    private StoreProductService storeProductService;

    @PostMapping
    public ResponseEntity<StoreProduct> createProduct(@RequestBody StoreProduct product) {
        return ResponseEntity.ok(storeProductService.save(product));
    }

    @GetMapping("/{id}")
    public ResponseEntity<StoreProduct> getProduct(@PathVariable Integer id) {
        return ResponseEntity.ok(storeProductService.findById(id));
    }

    @GetMapping
    public ResponseEntity<Page<StoreProduct>> getAllProducts(
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size,
            @RequestParam(defaultValue = "id") String sortBy) {
        PageRequest pageRequest = PageRequest.of(page, size, Sort.by(sortBy));
        return ResponseEntity.ok(storeProductService.findAll(pageRequest));
    }

    @PutMapping("/{id}")
    public ResponseEntity<StoreProduct> updateProduct(
            @PathVariable Integer id,
            @RequestBody StoreProduct product) {
        product.setId(id);
        return ResponseEntity.ok(storeProductService.update(product));
    }

    @DeleteMapping("/{id}")
    public ResponseEntity<Void> deleteProduct(@PathVariable Integer id) {
        storeProductService.deleteById(id);
        return ResponseEntity.ok().build();
    }
}
